package com.workingpub.commons.jdbc.builder.internal;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.workingpub.commons.jdbc.binding.ChooseEntry;
import com.workingpub.commons.jdbc.builder.BuildContext;
import com.workingpub.commons.jdbc.builder.LogicResolver;
import com.workingpub.commons.jdbc.builder.ResolverFactory;
import com.workingpub.commons.jdbc.builder.ognl.OgnlEvaluator;

@Service
public class ChooseResolver implements LogicResolver {
	@Autowired
	private ResolverFactory resolverFactory;

	@Override
	public List<Object> getContext(BuildContext buildContext, Object logicEntry) {
		if (logicEntry instanceof ChooseEntry) {
			ChooseEntry chooseEntry = (ChooseEntry) logicEntry;
			for (ChooseEntry.When entry : chooseEntry.getWhen()) {
				if (OgnlEvaluator.evaluateBoolean(entry.getTest(), buildContext.getRootParameter(),
						buildContext.getOtherParameters())) {
					return resolverFactory.resolve(buildContext, entry.getContent().toArray());
				}
			}
			if (null != chooseEntry.getOtherwise()) {
				return resolverFactory.resolve(buildContext, chooseEntry.getOtherwise().getContent().toArray());
			}
		}
		return null;
	}
}
